import axios from 'axios'

import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
// import localCatch from '@/utils/setCatch'

class MyRequest {
  instance: AxiosInstance
  constructor(config: AxiosRequestConfig) {
    this.instance = axios.create(config)
    this.instance.interceptors.request.use((config: any) => {
      const JsonToken = localStorage.getItem('token')
      if (JsonToken) {
        const token = JsonToken.substring(1, JsonToken.length - 1)
        config.headers.Authorization = token
      }
      return config
    })
    this.instance.interceptors.response.use(
      (res: AxiosResponse) => {
        return res.data
      },
      (err) => {
        return err
      }
    )
  }
  // 返回一个promise，便于在外面调用时拿到结果
  request<T>(config: AxiosRequestConfig): Promise<T> {
    return new Promise((resolve, reject) => {
      this.instance
        .request<any, T>(config)
        .then((res) => {
          resolve(res)
        })
        .catch((err) => {
          reject(err)
        })
    })
  }
  get<T>(config: AxiosRequestConfig): Promise<T> {
    return this.request({ ...config, method: 'get' })
  }
  post<T>(config: AxiosRequestConfig): Promise<T> {
    return this.request({ ...config, method: 'post' })
  }
  delete<T>(config: AxiosRequestConfig): Promise<T> {
    return this.request({ ...config, method: 'delete' })
  }
  patch<T>(config: AxiosRequestConfig): Promise<T> {
    return this.request({ ...config, method: 'patch' })
  }
}

export default MyRequest
